package com.sptpc.learnspring.controller;

import com.sptpc.learnspring.controller.request.NewDrinkRequest;
import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.service.ICategoryService;
import com.sptpc.learnspring.service.IDrinkService;
import com.sptpc.learnspring.vo.DrinkListVO;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    private IDrinkService drinkService;
    @Autowired
    private ICategoryService categoryService;

    // 前端使用json提交数据
    @PostMapping(value = "/add", consumes = {MediaType.APPLICATION_JSON_VALUE})
    public Drink addNewDrink(@RequestBody @Valid NewDrinkRequest newDrink) {
        log.info("创建新饮品{}", newDrink);
        Drink drink = new Drink();
        BeanUtils.copyProperties(newDrink, drink);
        drink.setCreateTime(LocalDate.now());
        drink = drinkService.addNewDrink(drink);
        log.info("创建成功");
        return drink;
    }

    @GetMapping("/")
    public List<Drink> listDrinks() {
        log.info("查询饮品菜单");
        return drinkService.getAllDrinks();
    }

    @GetMapping("/v2/")
    public List<Drink> listDrinks2(Integer page, Integer size) {
        Page<Drink> drinks = drinkService.getAllDrinks2(
                PageRequest.of(page, size));
        log.info("总记录数:{},\t总页数:{}", drinks.getTotalElements(), drinks.getTotalPages());
        return drinks.getContent();
    }

    @GetMapping("/{id}")
    public Drink getDrinkById(@PathVariable Long id) {
        log.info("查询饮品，id: {}", id);
        Optional<Drink> drinkOptional = drinkService.getDrinkById(id);
        if (drinkOptional.isPresent()) {
            return drinkOptional.get();
        } else {
            return null;
        }
    }

    @GetMapping("/v2/{id}")
    public Drink getDrinkById2(@PathVariable Long id) {
        Drink drink = drinkService.getDrinkById2(id);
        return drink;
    }

    @PostMapping("/")
    // 函数参数需与前端http参数名字相同
    public DrinkListVO searchDrinks(String key) {
        log.info("搜索饮品 key: {}", key);
        List<Drink> list = drinkService.searchDrinksByKey("%"+key+"%");
        DrinkListVO result = new DrinkListVO();
        result.setCount((long) list.size());
        result.setData(list);
        return result;
    }

    @GetMapping("/c/{cid}")
    // 通过分类id查找其下饮品
    public DrinkListVO getDrinksByCategory(@PathVariable Long cid) {
        log.info("查询分类下的饮品菜单");
        List<Drink> list = drinkService.searchDrinksByCategory(cid);
        DrinkListVO result = new DrinkListVO();
        result.setCount((long) list.size());
        result.setData(list);
        return result;
    }

    @PostMapping(value = "/batch",
            consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String batchAddDrinks(MultipartFile file) {
        if (file.isEmpty()) {
            return "创建失败";
        } else {
            try {
                List<Drink> drinks = new ArrayList<>();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(file.getInputStream()));
                String line="";
                while ((line=reader.readLine())!=null) {
                    String[] cols = line.split(",");
                    Category category = categoryService.getCategoryById(Long.parseLong(cols[2]));
                    Drink drink = Drink.builder().name(cols[0])
                            .price(Money.of(CurrencyUnit.of("CNY"), Double.parseDouble(cols[1])))
                            .createTime(LocalDate.now())
                            .category(category)
                            .build();
                    drinks.add(drink);
                }

                drinks = drinkService.batchAddDrinks(drinks);
                return "创建成功";
            } catch (IOException e) {
                return "创建失败";
            }
        }
    }
}
